<template>
  <div class="orderpreview-container nav-bar-top">
    <!-- 导航栏 -->
    <van-nav-bar class="nav-bar" title="确认订单" left-arrow @click-left="$router.back()"/>
    <!-- 地址信息 -->
    <div class="address-box circle-bg" v-if="addressLoading">
      <div class="receive-info">
        <div class="phone-box skeleton"><span class="name"></span><span class="phone"></span></div>
        <span class="address skeleton"></span>
      </div>
      <van-icon name="arrow" />
    </div>
    <div class="address-box circle-bg" @click="selectAddress" v-if="addressInfo.id && !addressLoading">
      <div class="receive-info">
        <div class="phone-box"><span class="name">{{addressInfo.receiverName}}</span><span class="phone">{{addressInfo.phone}}</span><span class="default" v-if="addressInfo.defaultFlag == '1'"><em>默认</em></span></div>
        <span class="address">{{addressInfo.provinceName+addressInfo.cityName+addressInfo.areaName+addressInfo.address}}</span>
      </div>
      <van-icon name="arrow" />
    </div>
    <div class="address-box circle-bg" @click="selectAddress" v-if="!addressInfo.id && !addressLoading">
      <div class="receive-info">
        <span class="empty"><van-icon name="plus" />点击添加地址</span>
      </div>
      <van-icon name="arrow" />
    </div>
    <!-- 普通商品列表 -->
    <div class="goods-list circle-bg" v-if="checkedCartList.length > 0 && !$route.query.type">
      <div class="order-goods-item" v-for="(cart, index) in checkedCartList" :key="index">
        <van-image :src="cart.goodsPic" />
        <div class="goods">
          <span class="title van-multi-ellipsis--l2">{{cart.goodsName}}</span>
          <span class="num">x{{cart.goodsNum}}</span>
          <div class="price"><span class="money">¥{{cart.goodsPrice | fentoyuan}}</span></div>
        </div>
      </div>
    </div>
    <!-- 秒杀商品列表 -->
    <div class="goods-list circle-bg" v-if="$route.query.type == 'secKill'">
      <div class="order-goods-item">
        <van-image :src="secKillGoodsInfo.goodsPic" />
        <div class="goods">
          <span class="title van-multi-ellipsis--l2">{{secKillGoodsInfo.goodsName}}</span>
          <span class="num">x1</span>
          <div class="price"><span class="money">¥{{secKillGoodsInfo.goodsSecKillPrice | fentoyuan}}</span></div>
        </div>
      </div>
    </div>
    <!-- 金额信息 -->
    <van-cell-group class="money-info circle-bg">
      <van-cell title="优惠券" is-link value="暂无优惠券" />
      <van-cell class="money" title="商品金额">
        <div slot="default">¥{{orderInfo.cartTotalMoney | fentoyuan}}</div>
      </van-cell>
      <van-cell class="money" title="运费">
        <div slot="default">¥{{orderInfo.orderFreightMoney | fentoyuan}}</div>
      </van-cell>
      <van-cell class="money" title="优惠">
        <div slot="default">¥{{orderInfo.orderDiscountMoney | fentoyuan}}</div>
      </van-cell>
    </van-cell-group>
    <!-- 总体信息 -->
    <div class="order-total">
      <span class="num">共<em>{{checkedCartList.length}}</em>件商品</span>
      <span>合计:</span>
      <span class="money">¥{{orderInfo.orderPayMoney | fentoyuan}}</span>
      <van-button :loading="submitLoading" loading-text="提交中..." @click="submitOrder" class="btn">提交订单</van-button>
    </div>
    <!-- 总体信息(秒杀) -->
    <div class="order-total">
      <span class="num">共<em>1</em>件商品</span>
      <span>合计:</span>
      <span class="money">¥{{orderInfo.orderPayMoney | fentoyuan}}</span>
      <van-button :loading="submitLoading" loading-text="提交中..." @click="submitSecKillOrder" class="btn">提交订单</van-button>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import constants from '@/config/constants'
import sysApi from '@/api/sysApi'
import orderApi from '@/api/orderApi'
import userApi from '@/api/userApi'

export default {
  data () {
    return {
      addressLoading: true,
      submitLoading: false,
      /* 收货地址 */
      addressInfo: {},
      /* 订单信息 */
      orderInfo: {
        cartTotalMoney: 0,
        orderDiscountMoney: 0,
        orderFreightMoney: 0,
        orderPayMoney: 0
      },
      /* 购物车 */
      cartIds: '',
      checkedCartList: [],
      /* 秒杀商品信息 */
      secKillGoodsInfo: {}
    }
  },
  computed: {
    ...mapState(['user', 'cartList', 'selectAddressInfo'])
  },
  created () {
    if(this.$route.query.type == 'secKill'){
      this.getSecKillOrderPreview();
    }else{
      this.getOrderPreview();
    }
  },
  methods: {
    /* 获取订单预览信息 */
    async getOrderPreview () {
      if(this.user){
        // 获取勾选的购物车
        var checkedCartList = new Array();
        var cartIdsArray = new Array();
        for(var i=0; i<this.cartList.length; i++){
          if(this.cartList[i].checked){
            cartIdsArray.push(this.cartList[i].id);
            checkedCartList.push(this.cartList[i]);
          }
        }

        //获取需要删除的购物车ids，逗号拼接
        var cartIds = '';
        for (var i = 0; i < cartIdsArray.length; i++) {
          cartIds += cartIdsArray[i]+ ",";
        }
        if (cartIdsArray.length > 0) {
          cartIds = cartIds.substr(0, cartIds.length - 1);
        }

        // 选中的购物车信息
        this.cartIds = cartIds;
        this.checkedCartList = checkedCartList;

        // 获取地址信息
        const result = await userApi.addressList(this.user.id);
        if(result.code == constants.SUCCESS){
          if(result.data.length > 0){
            if(this.selectAddressInfo){
              /* 有选中地址，进行匹配 */
              result.data.forEach(address => {
                if(this.selectAddressInfo.id == address.id){
                  this.addressInfo = address;
                }
              })
            }else{
              /* 没有选中地址，采用第一个地址 */
              this.addressInfo = result.data[0];
            }
          }
        }

        // 获取订单金额
        const orderResult = await orderApi.orderPreview({
          addressId: this.addressInfo.id ? this.addressInfo.id : '',
          cartIds: cartIds,
          couponId: '',
          memberId: this.user.id
        });
        if(orderResult.code == constants.SUCCESS){
          this.addressLoading = false;
          this.orderInfo = orderResult.data;
        }
      }
    },
    /* 获取秒杀订单预览信息 */
    async getSecKillOrderPreview () {
      // 获取地址信息
      const addessResult = await userApi.addressList(this.user.id);
      if(addessResult.code == constants.SUCCESS){
        if(addessResult.data.length > 0){
          if(this.selectAddressInfo){
            /* 有选中地址，进行匹配 */
            addessResult.data.forEach(address => {
              if(this.selectAddressInfo.id == address.id){
                this.addressInfo = address;
              }
            })
          }else{
            /* 没有选中地址，采用第一个地址 */
            this.addressInfo = addessResult.data[0];
          }
        }
      }
      this.addressLoading = false;

      //获取秒杀订单预览信息
      const result = await sysApi.secKillGoodsDetail({goodsId: this.$route.query.goodsId});
      if(result.code == constants.SUCCESS){
        this.orderInfo = {
          cartTotalMoney: result.data.goodsPrice,
          orderFreightMoney: 0,
          orderDiscountMoney: result.data.goodsPrice - result.data.goodsSecKillPrice,
          orderPayMoney: result.data.goodsSecKillPrice
        };
        this.secKillGoodsInfo = result.data;
      }
    },
    /* 选中地址 */
    selectAddress () {
      this.$router.push({path: '/address', query: {edit: true, id: this.addressInfo.id ? this.addressInfo.id : ''}})
    },
    /* 提交订单 */
    async submitOrder () {
      if(this.addressInfo.id){
        this.$toast.loading('生成订单中');
        this.submitLoading = true;
        const result = await orderApi.createOrder({
          addressId: this.addressInfo.id ? this.addressInfo.id : '',
          cartIds: this.cartIds,
          couponId: '',
          memberId: this.user.id
        });
        if(result.code == constants.SUCCESS){
          this.$toast.clear();
          this.$router.replace({path: '/orderPay', query: {id: result.data.id}});
          this.submitLoading = false;
        }
      }else{
        this.$toast.fail("请选择收货地址!");
      }
    },
    /* 提交秒杀订单 */
    async submitSecKillOrder () {
      if(this.addressInfo.id){
        this.$toast.loading('生成订单中');
        this.submitLoading = true;
        const result = await orderApi.createSecKillOrder({
          memberId: this.user.id,
          addressId: this.addressInfo.id ? this.addressInfo.id : '',
          secKillId: this.$route.query.secKillId
        });
        if(result.code == constants.SUCCESS){
          this.$toast.clear();
          this.$router.replace({path: '/orderPay', query: {id: result.data.id}});
          this.submitLoading = false;
        }
      }else{
        this.$toast.fail("请选择收货地址!");
      }
    }
  }
}
</script>

<style lang="scss">
.orderpreview-container{
  margin-bottom: 70px;
  padding-top: 5px;

  .address-line{
    margin: 10px 0;
    display: block;
    position: relative;
  }
  .goods-list{
    background: #fff;
    margin-bottom: 10px;
    padding: 0px 15px;
  }
  .money-info{
    .van-cell{
      padding-left: 0;
      padding-right: 0;
    }
    .money{
      .van-cell__value{
        color: #e1212b;
      }
    }
  }
  .order-total{
    border-top: 1px solid #f6f6f6;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    right: 0;
    height: 60px;
    width: 100%;
    padding-right: 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    span{
      font-size: 14px;
      color: #999;
    }
    .num{
      margin-right: 10px;
      em{
        font-style: normal;
        margin: 0px 5px;
      }
    }
    .money{
      margin-left: 5px;
      margin-right: 10px;
      color: #e1212b;
      font-size: 14px;
    }
    .btn{
      height: 35px;
    }
  }
}
</style>
